
const app = getApp()
import prizeApi from '../../api/prizeApi'
import msgCheck from '../../util/msgCheck'

import imgCheck from '../../util/imgCheck'
import uploadImgList from '../../util/uploadImgList'
import formatDateTime from '../../util/formatDateTime'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prize: '',

    content: '',
    imgList: [],
    fileList: [],
    date:'',
 
    deleteFiles: [],

    typeList: [
        {name: '实物品', value: 0},
        {name: '虚拟物品', value: 1}
    ],
    typeIndex: 0,

    open: true,
    avatarUrl: '',
    nickname: ""
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    
    this.setData({
      action: options.action
    })

    await app.getOpenid()

    this.setDate()

    if(options.action == 'update'){
      
      await this.getDetail(options.prizeId)
    } 
  },
  setDate(){
    let now = new Date()
    let time = now.getTime() + 1000 * 3600 * 2
    now = new Date(time)
    let str = formatDateTime(now, 'yyyy-MM-dd HH:mm')
    
    this.setData({
      date: str
    })
  },
  async getDetail(prizeId){
    wx.showLoading({
      mask: true
    })

    var res = await prizeApi.getPrize(prizeId)
  
    wx.hideLoading()
    
    this.setData({
      content: res.content,
      imgList: res.imgList,
      fileList: res.fileList,
      prize: res,
      date: res.date,
      typeIndex: res.type
    })
    
  },
  typeChange(e){
    let index = parseInt(e.detail.value)
    this.setData({
        typeIndex: index
    })
  },
  dateChange(e){
    this.data.date = e.detail
  }, 
  previewImage(e){
    var url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: this.data.imgList,
      current: url
    })
  },

  contentInput: function(e) {
    var val = e.detail.value;

    this.setData({
      content: val
    });
  },
  switchOpen(e){
    var val = e.detail.value;
    this.setData({
      open: val
    })
  },
  chooseImage:function(){
    wx.chooseMedia({
      count: 9 - this.data.imgList.length,
      mediaType: ['image'],
      success: (res) => {
        let list = res.tempFiles.map(obj => obj.tempFilePath)
        const tempFilePaths = this.data.imgList.concat(list)
        this.setData({
          imgList: tempFilePaths
        })
      }
    })
  },

  delImg(e){
  
    var index = e.currentTarget.dataset.index
    this.data.imgList.splice(index,1)
    var fileIds = this.data.fileList.splice(index,1)
    if(fileIds[0]){
      this.data.deleteFiles.push(fileIds[0])
    }
    this.setData({
      imgList: this.data.imgList
    })
  },
  onChooseAvatar(e){
    if(this.data.nickname){
      this.addPrize()
      return
    }
    this.selectComponent('#avatarNickname').open()
   
  },
  avatarNicknameConfirm(e){
    console.log(e)
    this.setData({
      avatarUrl: e.detail.avatarUrl,
      nickname: e.detail.nickname,
    })
    this.addPrize()
  },

  submit(){
    // 活动开奖通知
    // wx.requestSubscribeMessage({
    //   tmplIds: ['FdxWMtATv2zBhSEYu5rG0TnNVNu5H3CLSAfnD6S5xKA'],
    //   success (res) { 
    //     console.log(res)
    //   },
    //   fail(res){
    //     console.log(res)
    //   }
    // })

  
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.getUserProfile({
      desc: '用于抽奖中人员的显示',
      success: (res) => {
        console.log('用户信息授权',res)
        
        const userInfo = res.userInfo;
        if(userInfo){
          wx.setStorageSync('authorizedInfo', res)
          wx.setStorageSync('userInfo', userInfo)
          app.globalData.userInfo = userInfo
          this.addPrize()
        }
      },
      fail (e) {
       
      },
      complete(){
        wx.hideLoading();
      }
    })
    
  },

  async addPrize(){
    let pass = await msgCheck(this.data.content)
   if(!pass){
      return
   }

   pass =  await imgCheck(this.data.imgList)
   if(!pass){
    return
 }
     

    if(this.data.imgList.length == 0 && (!this.data.content)){
      wx.showToast({
        title:'没有可提交的内容',
        icon:'none'
      })
      return 
    }


    wx.showLoading({
      mask:true
    })
    var res = await uploadImgList(this.data.imgList, this.data.fileList)
    
    
    var params = {
      content:  this.data.content,
      fileList: res.map((f) => f.fileID),
      imgList: res.map((f) => f.tempFileURL),
      date:  this.data.date,
      type: this.data.typeList[this.data.typeIndex].value,
      open: this.data.open
    }


    if(this.data.action == 'update') {
      
      params.id = this.data.prize._id
      var paramsCopy = JSON.parse(JSON.stringify(params))
      var data = await prizeApi.updatePrize(params)
      
      data = await wx.cloud.deleteFile({
        fileList: this.data.deleteFiles
      })
      
      paramsCopy.type = 'prize'
    
      wx.setStorageSync('updatePrize', paramsCopy)
      wx.navigateBack()
    } else {
        let userInfo = wx.getStorageSync('userInfo')
        params.openid = app.globalData.openid
        params.avatarUrl = this.data.avatarUrl
        params.nickName = this.data.nickname
        params.status = 0
        params.top = 0
       
        var data = await prizeApi.addPrize(params)
        wx.showToast({
            title: '添加成功',
        })
        
        params.id = data
        params.type = 'prize'
    

        wx.setStorageSync('prizeListRefresh', 1)

        wx.redirectTo({
            url: '/prize/prizeDetail/prizeDetail?prizeId=' + data
        })

        
    }
    wx.hideLoading()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})